﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace ConfigManager.Core.Instructions
{
    public class OpenSectionInstruction : XmlInstruction
    {
        private XmlNode _endNode;
        private List<XmlInstruction> _childInstructions = new List<XmlInstruction>();

        #region Properties
        /// <summary>
        /// Gets or sets the end XML node.
        /// </summary>
        /// <value>The end node.</value>
        public XmlNode EndNode
        {
            get { return _endNode; }
            set { _endNode = value; }
        }

        /// <summary>
        /// Gets or sets the child instructions.
        /// </summary>
        /// <value>The child instructions.</value>
        public List<XmlInstruction> ChildInstructions
        {
            get { return _childInstructions; }
            set { _childInstructions = value; }
        }
        #endregion

        /// <summary>
        /// Sets the value instruction.
        /// </summary>
        /// <param name="xmlDoc">The XML doc.</param>
        /// <param name="node">The node.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The data.</param>
        public OpenSectionInstruction(XmlDocument xmlDoc, XmlNode node, IDictionary<string, string> parameters)
            : base ( xmlDoc, node, parameters)
        {
        }
        
        /// <summary>
        /// Runs this instruction.
        /// </summary>
        public override void Run()
        {
            if (PassesConditions())
            {
                foreach (XmlInstruction childInst in ChildInstructions)
                    childInst.Run();
            }
            else
            {
                bool foundEndNode = false;
                XmlNodeList nodes = Node.ParentNode.ChildNodes;
                for (int i = nodes.Count - 1; i >= 0; i--)
                {
                    if (!foundEndNode)
                    {
                        if (nodes[i] == EndNode)
                            foundEndNode = true;
                        continue;
                    }
                    if (nodes[i] == Node)
                        break;

                    DeleteNode(nodes[i]);
                }
            }

            DeleteNode(EndNode);
            base.Run();
        }
    }
}
